import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr

from util.LogHelper import Log


class EmailHelper:
    MAIL_SERVER = 'smtp.163.com'
    MAIL_USERNAME = '18310496963@163.com'  # 发件人
    EMAIL_FROM_NAME = 'Yuanzhijia@163.com'
    MAIL_PASSWORD = 'HNftBjdG8Q93Awqk'  # 发送者授权码

    @classmethod
    def sendEmail(cls, to_str, cc_str, subject, text):
        msg = MIMEMultipart()

        msg['From'] = formataddr(pair=(cls.EMAIL_FROM_NAME, cls.MAIL_USERNAME))
        if to_str is None:
            to_str = ''
        if cc_str is None:
            cc_str = ''

        msg['To'] = to_str  # 收件人，将列表转换为字符串
        msg["Cc"] = cc_str  # 抄送人，将列表转换为字符串
        msg['Subject'] = subject  # 邮件主题
        msg.attach(MIMEText(text, 'plain', 'utf-8'))  # 格式化邮件内容，编码为utf-8

        mail_server = None
        try:
            mail_server = smtplib.SMTP(cls.MAIL_SERVER, 25)
            mail_server.login(cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
            mail_server.sendmail(cls.MAIL_USERNAME, to_str + cc_str, msg.as_string())
            mail_server.close()  # 关闭连接
            Log.getEmaillogger().info(f'to: {to_str}, cc: {cc_str}, subject: {subject}, text: {text}')

            return True
        except Exception as e:
            Log.getlogger().error(f'send email failed! message: {e}')
            return False
        finally:
            mail_server.close()
